package com.lagou.rabbitmqdemo.db;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderDB {
    public static Map<String, String> state = new HashMap<>();

    static {
        state.put("0", "待支付");
        state.put("1", "已支付");
        state.put("2", "过期");
    }


    /**
     * 所有的订单
     * key为订单编号
     * value为订单状态 0-待支付 1-已支付 2-过期
     */
    public static Map<String, String> orders = new HashMap<>();

    /**
     * 用户订单列表
     */
    public static Map<String, List<String>> users = new HashMap<>();

    /**
     * 加订单
     * @param userId
     * @param orderNo
     */
    public static void add(String userId, String orderNo){
        List<String> list = users.get(userId);
        if (list == null) {
            list = new ArrayList<>();

            users.put(userId, list);
        }
        list.add(orderNo);

        // 添加订单 状态为待支付
        orders.put(orderNo, "0");
    }

    /**
     * 完成支付
     * @param orderNo
     */
    public static void complete(String orderNo) {
        orders.put(orderNo, "1");
    }

    /**
     * 设置过期
     * @param orderNo
     */
    public static boolean expire(String orderNo) {
        boolean isPay = checkIsPay(orderNo);
        if (isPay) return false;
        orders.put(orderNo, "2");

        return true;
    }

    /**
     * 检查是否过期
     * @return
     */
    public static boolean checkExpire(String orderNo){
        String state = orders.get(orderNo);
        if ("2".equals(state)){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查是否支付
     * @return
     */
    public static boolean checkIsPay(String orderNo){
        String state = orders.get(orderNo);
        if ("1".equals(state)){
            return true;
        } else {
            return false;
        }
    }

    public static Map<String, String> getOrderList(String userId){
        List<String> orderNos = users.get(userId);
        if (orderNos == null) return null;

        Map<String, String> result = new HashMap<>();
        orderNos.forEach(orderNo -> result.put(orderNo, orders.get(orderNo)));

        return result;
    }

}
